package com.duanjc.mdtool.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.duanjc.mdtool.service.MdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileFilter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * [一句话描述该类的功能]
 *
 * @author : [duanjiangcheng]
 * @version : [v1.0]
 * @createTime : [2023/3/24 14:55]
 */
@Slf4j
@Service
public class MdServiceImpl implements MdService {
    /**
     * 获取文件列表
     *
     * @param path path
     * @return List
     */
    @Override
    public List<File> getFilesList(String path) {
        return FileUtil.loopFiles(new File(path), file -> {
            final String path1 = file.getPath();
            if (path1.endsWith(".md")) {
                return true;
            }
            return false;
        });
    }

    /**
     * 给文件添加名称
     *
     * @param fileList fileList
     */
    @Deprecated
    @Override
    public void appendName(List<File> fileList) {
        //临时文件集合
        List<File> tmpFiles = new ArrayList<>();
        //待删除的文件集合
        List<File> emptyFiles = new ArrayList<>();


        Iterator<File> it = fileList.iterator();
        while (it.hasNext()){
            File file = it.next();
            String title = "#" + "\u0020" + FileUtil.getPrefix(file);
            log.info("生成标题：{}",title);
            List<String> context = FileUtil.readLines(file, StandardCharsets.UTF_8);
            if(!CollUtil.isEmpty(context)){
                //首行是否包含标题
                if (!context.get(0).equals(title)) {
                    //创建临时文件
                    log.info("临时文件名称：{}", file.getPath() + RandomUtil.randomLong(10000));
                    File tmpFile = FileUtil.touch(new File(file.getPath() + RandomUtil.randomLong(10000)));
                    //追加标题
                    FileUtil.appendString(title, tmpFile, StandardCharsets.UTF_8);
                    //追加内容
                    FileUtil.appendLines(context, tmpFile, StandardCharsets.UTF_8);
                    tmpFiles.add(tmpFile);
                }
            } else {
                FileUtil.del(file);
            }
        }


        Map<String ,Object> resultMap = new HashMap<String, Object>();
        tmpFiles.forEach(item -> {
            String fileName = FileUtil.getPrefix(item);
            String path = item.getParent();
            boolean del = FileUtil.del(new File(path + FileUtil.FILE_SEPARATOR + fileName + ".md"));
            if (del) {
                FileUtil.rename(item, fileName+".md", true);
            }
            resultMap.put(fileName, del);
            log.info("修改文件名结果"+resultMap);
        });
    }

    @Override
    public void appendContent(List<File> fileList, String oldStr, String newStr) {
        String reg = "[^0-9a-zA-Z\u4e00-\u9fa5]+";
        //临时文件集合
        List<File> tmpFiles = new ArrayList<>();

        Iterator<File> it = fileList.iterator();
        while (it.hasNext()){
            File file = it.next();
            String title = "#" + "\u0020" + FileUtil.getPrefix(file).replaceAll(reg,"");

            //String newTile = FileUtil.getPrefix(file).replaceAll(reg,"");

            log.info("生成标题：{}",title);
            List<String> context = FileUtil.readLines(file, StandardCharsets.UTF_8);
            List<String> newContext = context.stream()
                    .map(i-> i.replaceAll(oldStr,newStr)).collect(Collectors.toList());

            //创建临时文件
            log.info("临时文件名称：{}", file.getPath() + RandomUtil.randomLong(10000));
            File tmpFile = FileUtil.touch(new File(file.getPath() + RandomUtil.randomLong(10000)));
            if(!CollUtil.isEmpty(context)){
                //首行是否包含标题
                if (!context.get(0).equals(title)) {
                    //追加标题
                    FileUtil.appendString(title, tmpFile, StandardCharsets.UTF_8);
                }
            }
            //追加内容
            FileUtil.appendLines(newContext, tmpFile, StandardCharsets.UTF_8);
            tmpFiles.add(tmpFile);
            FileUtil.del(file);
        }


        Map<String ,Object> resultMap = new HashMap<String, Object>();
        tmpFiles.forEach(item -> {
            String fileName = FileUtil.getPrefix(item).replaceAll(reg,"");
            String path = item.getParent();
            boolean del = FileUtil.del(new File(path + FileUtil.FILE_SEPARATOR + fileName + ".md"));
            if (del) {
                FileUtil.rename(item, fileName+".md", true);
            }
            resultMap.put(fileName, del);
            log.info("修改文件名结果"+resultMap);
        });
    }
}
